/**
 * axios工具
 */
import axios from 'axios'
import router from '@/router'
import store from '@/store'
//1.删除多余依赖

// 创建axios实例
const service = axios.create({
    //2.修改后端接口请求url路径
    baseURL: "http://127.0.0.1:8081/business",
    //3.修改请求超时时间为5秒
    timeout: 5000
})

// request拦截器
service.interceptors.request.use(
    config => {
        //获取token的值
        let authorizationTokenValue = localStorage.getItem("token")
        if (authorizationTokenValue && authorizationTokenValue != "") {
            //将token的值放入请求头中
            config.headers['token'] = authorizationTokenValue
        }
        return config;
    },
    error => {
        Promise.reject(error)
    },
)

// response 拦截器
service.interceptors.response.use(
    response => {
        //从返回信息中获取数据
        let responseData = response.data
        //4.数据中状态码信息判断,进行相应操作
        if (responseData.code === 200) {
            //200--成功
            return response
        } else if(responseData.code === 402) {
          //自定义异常状态码信息
            //弹框提示错误信息
            alert(responseData.msg)
          //调用自定义重置方法
            store.commit("resetStore")
          //跳转至登录页面
            router.push('/')
        } else {
            responseData.msg = responseData.msg == '' ? '系统异常！' : responseData.msg
          //弹框
          alert(responseData.msg);
          return Promise.reject(responseData.msg)
        }

        return responseData
    },
    error => {
        let code = 0
        try {
            code = error.response.data.status
        } catch (e) {
            if (error.toString().indexOf('Error: timeout') !== -1 || error.toString().indexOf('Error: Network Error') !== -1) {
               alert('网络请求错误！')
                return Promise.reject(error)
            }
        }
        return Promise.reject(error)
    }
)
export default service
